<template>
	<view
		class="main"
		:style="{
			'--status-bar-height': state.statusBarHeight + 'px',
			'--head-top': state.headTop + 'px'
		}"
	>
		<view
			class="head"
			:style="{
				backgroundImage: `url(${getFileUrl('0x72412283')})`,
				paddingTop: state.statusBarTop + 'px'
			}"
		>
			<view class="search u-flex-between u-flex-y-center" @tap.stop="clickSearch">
				<view class="search_icon">
					<image :src="getFileUrl('0x72410082.webp')" mode=""></image>
				</view>
				<input type="text" @confirm.stop="clickSearch" disabled @blur.stop="clickSearch" confirm-type="search" v-model="state.keyword" placeholder="搜索客户" />
				<view class="search_txt">搜索</view>
			</view>
			<view class="tabs">
				<u-tabs
					ref="tabsRef"
					:list="state.tabs"
					keyName="label"
					:activeStyle="{ color: '#222', fontWeight: 700 }"
					:inactiveStyle="{ color: '#848D99', fontWeight: 400, 'font-size': '30rpx' }"
					:lineWidth="15"
					:scrollable="false"
					lineColor="#486CF6"
				></u-tabs>
			</view>
		</view>
		<scroll-view scroll-y class="list" @scrolltolower="scrolltolower">
			<Card v-if="state.dataList" :dataList="state.dataList" :cancelReason="state.cancelReason" />

			<view class="empty flex_center" v-if="state.dataList.length === 0 && state.loadConfig.status !== 'loading'">
				<u-empty textColor="#788DAB" :width="115" :height="216" :icon="getFileUrl('0x72412311.webp')" text="暂无工单"></u-empty>
			</view>
			<block v-else>
				<u-loadmore :status="state.loadConfig.status" :loadingText="state.loadConfig.loadingText" nomore-text=" " />
			</block>
			<!-- 占位 -->
			<view style="height: 1px"></view>
		</scroll-view>
	</view>
</template>

<script lang="ts" setup>
import { reactive, getCurrentInstance, onMounted } from "vue";
import { getFileUrl, getEleInfo } from "@/utils/common/index";
import { getOrderList } from "@/api/workOrder";
import { dict } from "@/api/common";
import Card from "./components/Card.vue";
import { getStatus, options } from "./status";

const instance = getCurrentInstance(); // 获取组件实例
const { height, top } = uni.getMenuButtonBoundingClientRect();

// status '0待服务 1已分配师傅 2已上门 3服务中 4服务完成 5已取消',
const state = reactive({
	keyword: "",
	statusBarTop: top || 32,
	statusBarHeight: height || 32,
	tabIdx: 0,
	headTop: 113,
	tabs: [
		{
			label: "全部",
			value: "",
			count: 0
		},
		...options
	],
	loadConfig: {
		status: "loading",
		loadingText: "加载中"
	},
	dataList: [],
	pageNo: 1,
	total: 0,
	load: true,
	cancelReason: {}
});

onMounted(() => {
	getEleInfo(".list", instance).then((res) => {
		state.headTop = res.top;
	});
});

const clickSearch = () => {
	uni.navigateTo({
		url: `/myPagesA/pages/workOrder/search`
	});
	// state.pageNo = 1;
	// getList();
};

// const refresherrefresh = () => {
// };

const clickTab = (idx: number) => {
	state.tabIdx = idx;
	state.pageNo = 1;
	state.dataList = [];
	getList();
};

// 触底加载
const scrolltolower = () => {
	if (state.total > state.dataList.length && state.loadConfig.status !== "loading") {
		state.pageNo += 1;
		getList();
	}
};

const getList = () => {
	state.loadConfig.status = "loading";
	const params: { [key: string]: any } = {
		pageNo: state.pageNo,
		pmNameSearch: state.keyword ? `*${state.keyword}*` : "",
		pageSize: 20,
		// customerViewStatus: state.tabs[state.tabIdx].value
		statusList: state.tabs[state.tabIdx].value
	};
	// 已完成的话 需要加上已支付完成状态
	// if (state.tabIdx===0) {
	// 	params.payStatus = '0';
	// }else if(state.tabIdx===1){
	// 	params.payStatus = '1';
	// }

	getOrderList(params)
		.then((res) => {
			console.log("res", res);
			if (res.data.code !== 200) throw res.data.message;
			let { total, records } = res.data.result;
			records = records.map((item: any) => {
				const { manpowerAmount, materialAmount, visitAmount } = item;
				const price = Number(((manpowerAmount || 0) + (materialAmount || 0) + (visitAmount || 0)).toFixed(2));
				// 提成 【工程师】提交【服务方案】后，才出现工程师的提成，提成为【服务费/上门费的30%】（不含材料费）  优先用服务费计算
				const mPrice = Number(((manpowerAmount || 0) * 0.3).toFixed(2));
				const vPrice = Number(((visitAmount || 0) * 0.3).toFixed(2));
				const deductPrice = mPrice || vPrice;
				return {
					...item,
					price,
					tabIdx: state.tabIdx,
					deductPrice
				};
			});
			state.dataList = params.pageNo == 1 ? records : [...state.dataList, ...records];
			state.total = total;

			const timer = setTimeout(() => {
				if (total === state.dataList.length) {
					state.loadConfig.status = "nomore";
				} else {
					state.loadConfig.status = "loadmore";
				}
				clearTimeout(timer);
			}, 150);
		})
		.catch((err) => {
			console.error(err);
		})
		.finally(() => {});
};

/**
 * 获取统计
 */
const getStat = () => {
	state.tabs.forEach((tab, idx) => {
		const params = { statusList: tab.value, pageSize: 1, payStatus: "" };
		// if (idx === 0) {
		//   params.payStatus = "0";
		// } else if (idx === 1) {
		//   params.payStatus = "1";
		// } else delete params.payStatus;
		getOrderList(params).then((res) => {
			let { total } = res.data.result;
			tab.count = total;
		});
	});
};

const getReasonList = () => {
	Promise.all([dict("ORDER_CANCEL_REASON"), dict("ORDER_WORKER_CANCEL_REASON")])
		.then((res: any) => {
			const listMap = {};
			res[0].data.result = res[0].data.result.filter((v: any) => v.value !== "9");
			res.forEach((item: any) => {
				item.data.result.forEach((v: any) => {
					listMap[v.value] = v.title;
				});
			});
			state.cancelReason = listMap;
		})
		.catch((err) => {
			console.error(err);
		});
};

const showPage = () => {
	state.pageNo = 1;
	getStat();
	getList();
};

getList();
getStat();
getReasonList();
defineExpose({ showPage });
</script>

<style lang="scss" scoped>
view {
	box-sizing: border-box;
}
image {
	width: 100%;
	height: 100%;
}
.main {
	width: 100vw;
	height: 100vh;
	--main-pb: calc(110rpx + env(safe-area-inset-bottom) / 2);
	padding-bottom: var(--main-pb);
	// --head-top: 300rpx;
}
.head {
	position: sticky;
	top: 0;
	// height: var(--head-top);
	width: 100%;
	background-repeat: no-repeat;
	background-size: 100% 100%;
	// padding-left: 30rpx;
	// padding-right: 30rpx;
	background-color: #fff;
}
.list {
	height: calc(100% - var(--head-top));
	padding: 0 16rpx 0 16rpx;
	box-sizing: border-box;
	width: 100%;
	background-color: #f7f7f7;
}

.search {
	width: 500rpx;
	height: var(--status-bar-height);
	margin-top: calc((var(--status-bar-height) - var(--status-bar-height)) / 2);
	border-radius: 54rpx;
	background-color: #f7f8fa;
	font-size: 26rpx;
	justify-content: space-between;
	margin-left: 30rpx;
	@include flex;
	input {
		width: calc(100% - 200rpx);
	}
	.search_txt {
		width: 115rpx;
		line-height: 31rpx;
		color: #333333;
		border-left: 1px solid #e0e0e0;
		padding-left: 30rpx;
	}
	.search_icon {
		width: 69rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		image {
			width: 23rpx;
			height: 23rpx;
		}
	}
}
.empty {
	height: 100%;
	margin-top: -10%;
}
.tabs {
	color: #999999;
	font-size: 32rpx;
	padding: 0 12rpx 0 0;
	width: 100%;
	height: 100rpx;
	:nth-child(1).tab_item,
	:nth-child(3).tab_item {
		width: 29.07%;
	}
	:nth-child(3).tab_item {
		justify-content: flex-end;
	}
	:nth-child(2).tab_item {
		width: 41.86%;
		justify-content: center;
		::before {
			content: "";
			position: absolute;
			left: 0;
			top: 50%;
			transform: translateY(-50%);
			height: 24rpx;
			width: 1px;
			background-color: #bbbbbb;
		}
		::after {
			content: "";
			position: absolute;
			right: 0;
			top: 50%;
			transform: translateY(-50%);
			height: 24rpx;
			width: 1px;
			background-color: #bbbbbb;
		}
	}

	.tab_line {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 144rpx;
		height: 100%;
		view {
			width: 1px;
			height: 24rpx;
			background-color: #bbbbbb;
		}
	}
	.act_tab_item {
		color: #222222;
	}
	:nth-child(1).tab_item {
		padding-left: 0 !important;
	}
	:nth-child(3).tab_item {
		padding-right: 0 !important;
	}
	:nth-child(3).tab_item::after {
		display: none;
	}
	.tab_item {
		@include flex;
		// padding: 0 72rpx;
		font-weight: bold;
		position: relative;
		// width: calc((100% - 288rpx) / 3);
		:nth-child(1) {
			margin-right: 16rpx;
		}
	}
	// .tab_item::after {
	// 	content: '';
	// 	position: absolute;
	// 	right: 0;
	// 	top: 50%;
	// 	transform: translateY(-50%);
	// 	height: 24rpx;
	// 	width: 1px;
	// 	background-color: #bbbbbb;
	// }
}
</style>
